// pages/site/new-site/new-site.js
var httpUtil = require('../../../utils/httpUtil.js');
var uiUtil = require('../../../utils/uiUtil.js');
const app = getApp();
const mobile = /^1\d{10}$/;
var that;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    userLocation: null,//用户地理位置
    site:null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    that=this;
    let site;
    if (options.site){
      site = JSON.parse(options.site);
    }
    that.setData({
      site: site,
      userLocation: app.globalData.userLocation
    });
  },

  

  /**
   * 保存收货地址
   */
  saveUsedAddress(res){
    let value = res.detail.value;
    if(value.name==""){
      uiUtil.showToast("请填写联系人姓名");
    } else if (!mobile.test(value.phone)){
      uiUtil.showToast("请填写正确的手机号");
    } else if (value.area == "") {
      uiUtil.showToast("请选择地址");
    } else if (value.address == "") {
      uiUtil.showToast("请填写详细地址");
    } else if(that.data.site.id){
      that.getSite(value);
    } else {
      that.getNewSite(value);
    }
  },

  /**
   * 保存新收货地址
   */
  getNewSite(value){
    uiUtil.showLoading("请稍候..");
    httpUtil.PostRequest("saveUsedAddress", {
      name: value.name,
      phone: value.phone,
      area: value.area,
      address: value.address,
      lng: that.data.site.lng,
      lat: that.data.site.lat,
      label: that.data.site.name
    }, {
        success(res) {
          uiUtil.showToast("保存成功");
          that.lastPage();
        },
        fail(code, res) {
          uiUtil.showToast(res);
        },
        complete() { }
      })
  },

  /**
   * 修改旧收货地址
   */
  getSite(value) {
    uiUtil.showLoading("请稍候..");
    httpUtil.PostRequest("updateUsedAddress", {
      id: that.data.site.id,
      name: value.name,
      phone: value.phone,
      area: value.area,
      address: value.address,
      lng: that.data.site.lng,
      lat: that.data.site.lat,
      label: that.data.site.name
    }, {
        success(res) {
          uiUtil.showToast("保存成功");
          that.lastPage();
        },
        fail(code, res) {
          uiUtil.showToast(res);
        },
        complete() { }
      })
  },

  /**
   * 返回上一页
   */
  lastPage(){
    var pages = getCurrentPages();
    var lastPage = pages[pages.length - 2];
    lastPage.onResultRegisterSuccess();
    wx.navigateBack({
      delta: 1,
    });
  },


  /**
   * 选择地址
   */
  siteChange(){
    wx.chooseLocation({
      latitude: that.data.userLocation.pois[0].location.lat,
      longitude: that.data.userLocation.pois[0].location.lng,
      success(res){
        that.setData({
          "site.area": res.name,
          "site.lng": res.longitude,
          "site.lat": res.latitude
        })
      },
      fail(res){
        console.log(res);
      }
    });
  }
})